package com.blacksheep.mtm.service.Impl;

import com.alibaba.excel.EasyExcel;
import com.blacksheep.mtm.common.exception.XmallException;
import com.blacksheep.mtm.common.jedis.JedisClient;
import com.blacksheep.mtm.dao.TbMemberMapper;
import com.blacksheep.mtm.dao.TbSupplierMapper;
import com.blacksheep.mtm.dto.DtoUtil;
import com.blacksheep.mtm.dto.MemberDto;
import com.blacksheep.mtm.pojo.DemoData;
import com.blacksheep.mtm.pojo.common.DataTablesResult;
import com.blacksheep.mtm.pojo.manager.TbMember;
import com.blacksheep.mtm.pojo.manager.TbMemberExample;
import com.blacksheep.mtm.search.message.DemoDataListener;
import com.blacksheep.mtm.service.MemberService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MemberServiceImpl implements MemberService {

    final static Logger log = LoggerFactory.getLogger(MemberServiceImpl.class);

    @Autowired
    private  TbMemberMapper tbMemberMapper;
    @Autowired
    private  TbSupplierMapper supplierMapper;


    @Override
    public TbMember getMemberById(long memberId) {
        return null;
    }

    @Override
    public DataTablesResult getMemberList(int draw, int start, int length, String search, int[] state, String minDate, String maxDate, String orderCol, String orderDir) {
        DataTablesResult result = new DataTablesResult();

        PageHelper.startPage(start / length + 1, length);
        List<MemberDto> list = tbMemberMapper.selectListMemberInfo("%" + search + "%", state, minDate, maxDate, orderCol, orderDir);
        for (MemberDto memberDto:list){
            if (!StringUtils.isBlank(memberDto.getSupplierId())){
                String[] suppilers = memberDto.getSupplierId().split(",");
                String names = supplierMapper.selectSupplierName(suppilers);
                memberDto.setSupplierName(names);
            }
        }
        PageInfo<MemberDto> pageInfo = new PageInfo<>(list);
        result.setRecordsFiltered((int) pageInfo.getTotal());
        result.setDraw(draw);
        result.setData(list);
        return result;
    }

    @Override
    public DataTablesResult getDispatcherMemberList(int role, int draw, int start, int length, String search, int[] state, String minDate, String maxDate, String orderCol, String orderDir) {
        DataTablesResult result = new DataTablesResult();
        PageHelper.startPage(start / length + 1, length);
        List<MemberDto> list = tbMemberMapper.selectListMemberByRole(role, "%" + search + "%", state, minDate, maxDate, orderCol, orderDir);
        for (MemberDto memberDto:list){
            if (!StringUtils.isBlank(memberDto.getSupplierId())){
                String[] suppilers = memberDto.getSupplierId().split(",");
                String names = supplierMapper.selectSupplierName(suppilers);
                memberDto.setSupplierName(names);
            }
        }
        PageInfo<MemberDto> pageInfo = new PageInfo<>(list);
        result.setRecordsFiltered((int) pageInfo.getTotal());
        result.setDraw(draw);
        result.setData(list);
        return result;
    }




    @Override
    public TbMember getMemberByPhone(String phone) {

        List<TbMember> list;
        TbMemberExample example = new TbMemberExample();
        TbMemberExample.Criteria criteria = example.createCriteria();
        criteria.andPhoneEqualTo(phone);
        try {
            list = tbMemberMapper.selectByExample(example);
        } catch (Exception e) {
            throw new XmallException("Phone获取用户信息失败");
        }
        if (!list.isEmpty()) {
            list.get(0).setPassword("");
            return list.get(0);
        }
        return null;
    }

    @Override
    public TbMember getMemberByUsername(String username) {
        List<TbMember> list;
        TbMemberExample example = new TbMemberExample();
        TbMemberExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        try {
            list = tbMemberMapper.selectByExample(example);
        } catch (Exception e) {
            throw new XmallException("ID获取用户信息失败");
        }
        if (!list.isEmpty()) {
            list.get(0).setPassword("");
            return list.get(0);
        }
        return null;
    }

    @Override
    public TbMember addMember(MemberDto memberDto) {

        TbMember tbMember = DtoUtil.MemberDto2Member(memberDto);
        if (getMemberByUsername(tbMember.getUsername()) != null) {
            throw new XmallException("用户名已被注册");
        }
        if (tbMember.getRole() ==1 && StringUtils.isBlank(tbMember.getSupplierId())){
            throw new XmallException("行业用户请选择分组");
        }
        TbMember member = tbMemberMapper.selectMemberByPhoneAndRole(tbMember.getPhone(),tbMember.getRole());
        if (member != null) {
            throw new XmallException("手机号已被注册");
        }

        tbMember.setState(1);
        if (StringUtils.isBlank(tbMember.getRealname())){
            tbMember.setRealname(tbMember.getUsername());
        }
        if (tbMemberMapper.insertSelective(tbMember) != 1) {
            throw new XmallException("添加用户失败");
        }
        return tbMember;
    }

    @Override
    public TbMember updateMember(Long id, MemberDto memberDto) {

        TbMember tbMember = DtoUtil.MemberDto2Member(memberDto);
        if (tbMember.getRole() ==1 && tbMember.getSupplierId()==null){
            throw new XmallException("行业用户请选择分组");
        }
        if (tbMemberMapper.updateByPrimaryKeySelective(tbMember) != 1) {
            throw new XmallException("更新用户信息失败");
        }
        return getMemberById(id);
    }

    @Override
    public TbMember alertMemberState(Long id, Integer state) {

        TbMember tbMember = tbMemberMapper.selectByPrimaryKey(id);
        tbMember.setState(state);

        if (tbMemberMapper.updateByPrimaryKeySelective(tbMember) != 1) {
            throw new XmallException("修改用户状态失败");
        }
        return getMemberById(id);
    }



    @Override
    public TbMember getMemberByEditPhone(Long id, String phone) {
        return null;
    }

    @Override
    public TbMember getMemberByEditUsername(Long id, String username) {
        return null;
    }

    @Override
    public DataTablesResult chooseMemberList(int draw, int start, int length, int[] state, String seach, String orderColumn, String orderDir) {
        return null;
    }

    @Override
    public Integer deletBatch(Long[] ids) {
        int result = tbMemberMapper.deleteBatch(ids);
        if (result<1){
            throw  new XmallException("删除失败");
        }
        return null;
    }


    /**
     * 随机生成6位随机验证码
     * 方法说明
     *
     * @return String
     */
    private String createRandomVcode() {
        //验证码
        String vcode = "";
        for (int i = 0; i < 6; i++) {
            vcode = vcode + (int) (Math.random() * 9);
        }
        return vcode;
    }

}
